//
// Screenshot.h
//
// Created by Simon Madine on 29/04/2010.
// Copyright 2010 The Angry Robot Zombie Factory.
// - Converted to Cordova 1.6.1 by Josemando Sobral.
// MIT licensed
//
// Modifications to support orientation change by @ffd8
//

#import <Cordova/CDV.h>
#import "Screenshot.h"

@interface Screenshot ()

@property (nonatomic, assign, readonly) UIEdgeInsets safeAreaInset;

@end



@implementation Screenshot

@synthesize webView;


- (UIImage *)getScreenshot
{
//	UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
//	CGRect rect = [keyWindow bounds];
//	UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
//	[keyWindow drawViewHierarchyInRect:keyWindow.bounds afterScreenUpdates:NO];
//	UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//	UIGraphicsEndImageContext();
	return nil;
}

- (void)saveScreenshot:(CDVInvokedUrlCommand*)command{
    NSDictionary *parameter;
    if (command.arguments.count > 0) {
        parameter = command.arguments.firstObject;
    }
    if (!parameter) {
        return;
    }
    CGFloat autoNavigationHeight = [self navigationHeight];
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat width = [parameter[@"width"] floatValue];
    CGFloat height = [parameter[@"height"] floatValue];
    CGSize imageSize = CGSizeMake(screenSize.width, screenSize.width*height/width);
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(screenSize.width, imageSize.height+autoNavigationHeight), YES, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    UIRectClip(CGRectMake(0,autoNavigationHeight,screenSize.width,imageSize.height));
    [[UIApplication sharedApplication].keyWindow.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, autoNavigationHeight*[UIScreen mainScreen].scale, screenSize.width*[UIScreen mainScreen].scale, imageSize.height*[UIScreen mainScreen].scale));
    UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:[UIScreen mainScreen].scale orientation:(UIImageOrientationUp)];
    UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
    NSData *imageData = UIImageJPEGRepresentation(image,1);
    NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
	CDVPluginResult* pluginResult = nil;
    NSDictionary *jsonObj = @{@"image":base64Encoded};
	pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:jsonObj];
	NSString* callbackId = command.callbackId;
	[self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}

//保存完成后调用的方法
- (void) savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
    if (error) {
        NSLog(@"保存图片出错%@", error.localizedDescription);
    }
    else {
        NSLog(@"保存图片成功");
    }
}

- (UIEdgeInsets)safeAreaInset {
    if (@available(iOS 11.0, *)) {
        return [UIApplication sharedApplication].keyWindow.safeAreaInsets;
    }
    return UIEdgeInsetsZero;
}

- (BOOL)isHairHead {
    if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return self.safeAreaInset.left > 0.0f;
    }else {
        // ios12 非刘海屏状态栏 20.0f
        return self.safeAreaInset.top > 20.0f;
    }
}


-(CGFloat)navigationHeight{
    return [self isHairHead] ? 88 : 64;
}


- (void) getScreenshotAsURI:(CDVInvokedUrlCommand*)command
{
//	NSNumber *quality = command.arguments[0];
//	UIImage *image = [self getScreenshot];
//	NSData *imageData = UIImageJPEGRepresentation(image,[quality floatValue]);
    NSString *base64Encoded = @"111";
	NSDictionary *jsonObj = @{
	    @"URI" : [NSString stringWithFormat:@"data:image/jpeg;base64,%@", base64Encoded]
	};
	CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:jsonObj];
	[self.commandDelegate sendPluginResult:pluginResult callbackId:[command callbackId]];
}
@end
